#include "CF_Includes.h"

CCF_Input::CCF_Input(HINSTANCE instance)
{
  this->m_inctance = instance;
}

CCF_Input::~CCF_Input(void)
{
}

BOOL CCF_Input::InitDirect()
{
  return S_OK == DirectInput8Create( this->m_inctance, DIRECTINPUT_VERSION, 
    IID_IDirectInput8, (void**)&m_directInput, NULL);
}

BOOL CCF_Input::InitMouse( HWND hwnd )
{
  if( FAILED(this->m_directInput->CreateDevice( GUID_SysMouse, &this->m_mouseDevice, NULL )))
    return false;

  if( FAILED( this->m_mouseDevice->SetDataFormat( &c_dfDIMouse2 )) )
    return false;

  if( FAILED( this->m_mouseDevice->SetCooperativeLevel( hwnd, DISCL_EXCLUSIVE | DISCL_FOREGROUND ) ))
    return false;

  if( FAILED( this->m_mouseDevice->Acquire() ))
    return false;

  return true;
}

BOOL CCF_Input::InitKeyboard( HWND hwnd )
{
  if( FAILED(this->m_directInput->CreateDevice( GUID_SysKeyboard, &this->m_keyboardDevice, NULL ) ))
    return false;

  if( FAILED( this->m_keyboardDevice->SetDataFormat( &c_dfDIKeyboard )) )
    return false;

  if( FAILED( this->m_keyboardDevice->SetCooperativeLevel( hwnd, DISCL_FOREGROUND | DISCL_NONEXCLUSIVE) ))
    return false;

  if( FAILED( this->m_keyboardDevice->Acquire() ))
    return false;

  return true;
}

BOOL CCF_Input::QueryMouse()
{
  ZeroMemory( &m_mouseData, sizeof(m_mouseData) );

  if ( FAILED( m_mouseDevice->GetDeviceState( sizeof(m_mouseData), (LPVOID)&m_mouseData ) ) )
  {
    ZeroMemory( &m_mouseData, sizeof(DIMOUSESTATE2) );

    while ( m_mouseDevice->Acquire() == DIERR_INPUTLOST ){}
  }
  else
  {
    return true;
  }

  return false;
}
BOOL CCF_Input::QueryKeyboard()
{
  ZeroMemory( m_keyBuffer, sizeof(m_keyBuffer) );

  if ( FAILED( this->m_keyboardDevice->GetDeviceState( sizeof(m_keyBuffer), (LPVOID)&m_keyBuffer ) ) )
  {
//    ZeroMemory( m_keyBuffer, sizeof(m_keyBuffer) );
    while ( m_keyboardDevice->Acquire() == DIERR_INPUTLOST ){}
  }
  else
  {
    return true;
  }

  return false;
}
BOOL CCF_Input::Initialize( HWND hwnd )
{
  BOOL result = false;

  if( InitDirect())
  {
    result = InitMouse( hwnd ) && InitKeyboard( hwnd );
  }

  return result;
}
BOOL CCF_Input::Update()
{
  return QueryMouse() && QueryKeyboard();
}
BOOL CCF_Input::IsKeyDown(char key)
{
  m_keyTime[key] = timeGetTime();

  return m_keyBuffer[key] & 0x80;
}

BOOL CCF_Input::IsKeyPressAt( char key, int time )
{
  int currTime = timeGetTime();

  if(m_keyTime[key] <= (currTime - time))
  {
    m_keyTime[key] = currTime;

    return m_keyBuffer[key] & 0x80;
  }

  return false;
}

DIMOUSESTATE2* CCF_Input::GetMouseState()
{
  return &m_mouseData;
}
